const sqlite3 = require('sqlite3').verbose();

class DBUtil {
    constructor(dbPath) {
        this.db = new sqlite3.Database(dbPath);
    }

    execute(sql, params = []) {
        return new Promise((resolve, reject) => {
            this.db.run(sql, params, function(err) {
                if (err) {
                    console.error(`[${new Date().toISOString()}] SQL执行错误:`, {
                        sql,
                        params,
                        error: err.message
                    });
                    reject(err);
                } else {
                    resolve(this);
                }
            });
        });
    }

    query(sql, params = []) {
        return new Promise((resolve, reject) => {
            this.db.all(sql, params, (err, rows) => {
                if (err) {
                    console.error(`[${new Date().toISOString()}] SQL查询错误:`, {
                        sql,
                        params,
                        error: err.message
                    });
                    reject(err);
                } else {
                    resolve(rows);
                }
            });
        });
    }
}

module.exports = new DBUtil('student_answers.db');